<?php
/**
 * 雇主后台页面
 */
namespace website\controllers;

use common\models\Coupon;
use common\models\EmploymentAppeal;
use common\models\EmploymentSalary;
use Yii;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use common\helpers\Util;
use common\helpers\Pager;
use common\helpers\Render;
use common\helpers\Checker;
use common\server\sms\SmsCaptcha;
use common\server\recharge\RechargeServer;
use common\models\Category;
use common\models\User;
use common\models\UserCoupon;
use common\models\UserEvaluate;
use common\models\UserCollection;
use common\models\Recruit;
use common\models\RecruitApplicant;
use common\models\Employment;
use common\models\EmploymentPause;
use common\models\EmploymentRecharge;
use common\helpers\Uploader;


class EmployerController extends UserController {

    /**
     * 判断用户是否雇主
     * @param $action
     * @return bool
     * @throws \yii\base\ExitException
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if(parent::beforeAction($action)) {
            if($this->user->role != User::RoleEmployer) {
                if($this->isJson) {
                    Yii::$app->getResponse()->data = $this->json('Invalid.Request', '请稍后重试');
                }
                else {
                    Yii::$app->getResponse()->data = $this->error('请稍后重试', 'welcome/index');
                }
                // 发送response数据到页面
                Yii::$app->getResponse()->send();
                // 结束application
                Yii::$app->end();
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 雇主后台主页
     * @return mixed
     */
    public function actionIndex()
    {
        $recommendDesigner = User::search()->orderBy(['registor' => 'DESC', 'updated_at' => 'DESC'])->limit(21)->all();
        return $this->render('index', [
            'designers' => $recommendDesigner,
            'receiveCount' => RecruitApplicant::find()->alias('a')->leftJoin(Recruit::tableName().' as b', 'recruit_id = a.id and employer_id = '.$this->user->id)
                ->andWhere(['b.status' => [Recruit::StatusExamine, Recruit::StatusRelease]])
                ->andWhere(['!=', 'a.status', RecruitApplicant::StatusRevoke])->count()
        ]);
    }

    /**
     * 雇主注册页面
     * @return mixed
     */
    public function actionInformation()
    {
        $user = $this->user;
        // 参数异常，渲染错误页面
        if( ! $this->request->isPost) {
            return $this->render('information', [
                'user' => $user,
            ]);
        }
        if($user->information()) {
            $this->json('Already', '个人资料已填写，如需修改，请联系客服');
        }
        $params = $this->request->post();
        $checker = Checker::authentication(User::flyer('employer-information'), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
//        if( ! SmsCaptcha::validate($params['captcha'], 'user-information')) {
//            return $this->json('Invalid.Captcha', '验证码错误（Invalid Captcha）');
//        }
        $user->loads($params);
        if ( ! $user->validate()) {
            // 参数异常，渲染错误页面
            return $this->json('Invalid.Param', $this->buildModelError($user));
        }
        if ($user->save()) {
            // 保存成功
            return $this->json(SuccessCode, '保存成功');
        }
        // 参数异常，渲染错误页面
        return $this->json('System.Error', '提交失败，请重试');
    }

    /**
     * 我的钱包
     * @return mixed
     */
    public function actionWallet()
    {
        $salary = EmploymentSalary::find()
            ->where(['employer_id' => $this->user->id, 'status' => [EmploymentSalary::StatusInit, EmploymentSalary::StatusPaying]])
            ->sum('hires');
        return $this->render('wallet', [
            'user' => $this->user,
            'frozen' => $salary,
        ]);
    }

    /**
     * 招聘列表
     * @return mixed
     */
    public function actionRecruitList()
    {
        if( ! $this->user->information()) {
            return $this->error('请先完善个人资料', 'employer/information');
        }
        if( ! $this->isJson) {
            return $this->render('recruit-list');
        }
        $params['employer_id'] = $this->user->id;
        $query = Recruit::filterConditions(Recruit::initCondition(['employer_id'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * 招聘信息详情
     * @return mixed
     */
    public function actionRecruit()
    {
        if( ! $this->user->information()) {
            return $this->error('请先完善个人资料', 'employer/information');
        }
        $recruit = null;
        $reruitId = $this->request->get('id');
        if($reruitId && ( ! $recruit = Recruit::canEdit($reruitId, ['employer_id' => $this->user->id]))) {
            return $this->error('无效的招聘信息（Invalid Recruit）', 'employer/recruit-list');
        }
        if( ! $this->request->isPost) {
            return $this->render('recruit', [
                'recruit' => $recruit,
                'models' => Category::selector($this->params['designModelCategories']),
                'categories' => Category::selector($this->params['designCategories']),
            ]);
        }
        if( ! $recruit) {
            $recruit = new Recruit();
        }
        $params = $this->request->post();
        $checker = Checker::authentication(Recruit::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        $params['models'] = implode(',', $params['models']);
        $params['styles'] = implode(',', $params['styles']);
        // 如果预算小于阶段3，不需要后台审核直接发布
        if($params['budget'] < Recruit::BudgetThird) {
            $params['status'] = Recruit::StatusRelease;
        }
        $recruit->loads($params);
        $recruit->employer_id = $this->user->id;
        if( ! $recruit->validate()) {
            // 参数异常，渲染错误页面
            return $this->json('Invalid.Param', $this->buildModelError($recruit));
        }
        if($recruit->save()) {
            // 保存成功
            return $this->json(SuccessCode, '保存成功');
        }
        // 参数异常，渲染错误页面
        return $this->json('System.Error', '提交失败，请重试');
    }

    /**
     * 设计师简历投递列表
     * @return mixed
     */
    public function actionRecruitApplicant()
    {
        if( ! $recruit = Recruit::canEdit($this->request->get('id'))) {
            if($this->isJson) {
                return $this->json('Invalid.Recruit', '无效的招聘信息（Invalid Recruit）');
            }
            return $this->error('无效的招聘信息（Invalid Recruit）', 'employer/recruit-list');
        }
        if($recruit->employer_id != $this->user->id) {
            if($this->isJson) {
                return $this->json('Invalid.Recruit', '您只能修改查看属于您自己的招聘信息（Invalid Recruit）');
            }
            return $this->error('您只能修改查看属于您自己的招聘信息（Invalid Recruit）', 'employer/recruit-list');
        }
        if( ! $this->isJson) {
            return $this->render('recruit-applicant', [
                'recruit' => $recruit
            ]);
        }
        $params['recruit_id'] = $recruit->id;
        $params['status'] = RecruitApplicant::StatusRevoke;
        $query = RecruitApplicant::filterConditions(RecruitApplicant::initCondition(['recruit_id', ['status', '!=']], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('created_at desc, id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        $data['designer'] = ArrayHelper::index(User::find()->select('id, photo, gender, work_life, nickname, realname, skills, salary, star')
            ->where(['id' => ArrayHelper::getColumn($data['infos'], 'designer_id')])
            ->with('styles')->with('categories')
            ->asArray()->all(), 'id');
        foreach($data['designer'] as & $designer) {
            $designer['stylesString'] = implode(',', ArrayHelper::getColumn($designer['styles'], 'category_id'));
            $designer['categoriesString'] = implode(',', ArrayHelper::getColumn($designer['categories'], 'category_id'));
        }
        return $this->json($data);
    }

    /**
     * 雇佣列表
     * @return mixed
     */
    public function actionEmploymentList()
    {
        if( ! $this->isJson) {
            return $this->render('employment-list', [
                'status' => $this->request->get('status'),
            ]);
        }
        $params['status'] = $this->request->get('status');
        $params['employer_id'] = $this->user->id;
        $query = Employment::filterConditions(Employment::initCondition(['employer_id', 'status'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $date = date('Ymd');
        $data['infos'] = $query->with('designer')->orderBy(new Expression("finish > {$date} desc, finish asc"))->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        $pause = EmploymentPause::find()->where(['status' => [EmploymentPause::StatusInit, EmploymentPause::StatusConfirm], 'employment_id' => ArrayHelper::getColumn($data['infos'], 'id')])->asArray()->all();
        $data['pause'] = ArrayHelper::index($pause, 'employment_id');
        $appeal = EmploymentAppeal::find()->where(['status' => [EmploymentPause::StatusInit, EmploymentPause::StatusConfirm], 'employment_id' => ArrayHelper::getColumn($data['infos'], 'id')])->asArray()->all();
        $data['appeal'] = ArrayHelper::index($appeal, 'employment_id');
        $evaluate = UserEvaluate::find()->where(['employment_id' => ArrayHelper::getColumn($data['infos'], 'id')])->asArray()->all();
        $data['evaluate'] = ArrayHelper::index($evaluate, 'employment_id');
        $salary = EmploymentSalary::find()
            ->where(['employment_id' => ArrayHelper::getColumn($data['infos'], 'id'), 'status' => EmploymentSalary::StatusInit])
            ->andWhere(['<=', 'paydate', date('Ymd')])
            ->orderBy('paydate asc')
            ->asArray()->all();
        $data['salary'] = ArrayHelper::index($salary, 'employment_id');
        return $this->json($data);
    }
    /**
     * 下雇佣订单
     * return mixed
     */
    public function actionEmployment()
    {
        $employment = null;
        $employmentId = $this->request->get('id');
        if($employmentId && ( ! $employment = Employment::canEdit($employmentId, ['employer_id' => $this->user->id]))) {
            if( ! $this->request->isPost) {
                return $this->error('无效的雇佣信息（Invalid Employment）', 'employer/employment-list');
            }
            else {
                return $this->json('Invalid.Employment', '无效的雇佣信息');
            }
        }
        if( ! $this->request->isPost) {
            if(empty($employment)) {
                $designerId = $this->request->get('designer_id');
                $designer = User::canEdit($designerId);
                if( ! ($designer && $designer->active())) {
                    return $this->error('设计师状态异常，不能雇佣', 'employer/employment-list');
                }
            }
            else {
                if( ! in_array($employment->status, [Employment::StatusInit])) {
                    return $this->error('当前雇佣订单不能修改', 'employer/employment-list');
                }
                $designer = $employment->designer;
            }
            return $this->render('employment', [
                'employment' => $employment,
                'designer' => $designer,
            ]);
        }
        $params = $this->request->post();
        $checker = Checker::authentication(Employment::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if(Employment::isEmployed($params['designer_id'])) {
            return $this->json('Invalid.Param', '您与该名设计师存在正在进行中的雇佣关系，请不要重复雇佣哦');
        }
        if(empty($employment)) {
            $employment = new Employment();
            $employment->order_number = Employment::generateOrderNumber();
            $employment->employer_id = $this->user->id;
        }
        else {
            if( ! in_array($employment->status, [Employment::StatusInit])) {
                return $this->error('当前雇佣订单不能修改', 'employer/employment-list');
            }
        }
        $params['begin'] = str_replace('-', '', $params['begin']);
        $params['hires'] = bcmul($params['hires'], 100);
        $employment->loads($params);
        if ( ! $employment->validate()) {
            // 参数异常，渲染错误页面
            return $this->json('Invalid.Param', $this->buildModelError($employment));
        }
        // 计算配置信息
        if( ! $employment->initParams()) {
            return $this->json('System.Error', '提交失败，请重试');
        }
        if ($employment->save()) {
            // 保存成功
            return $this->json(SuccessCode, '保存成功');
        }
        // 参数异常，渲染错误页面
        return $this->json('System.Error', '提交失败，请重试');
    }
    /**
     * 确认雇佣订单
     * @return mixed
     */
    public function actionEmploymentOrder()
    {
        $employment = Employment::canEdit($this->request->get('id'), ['employer_id' => $this->user->id]);
        if( ! $this->request->isPost) {
            if(empty($employment)) {
                return $this->error('无效的雇佣信息（Invalid Employment）', 'employer/employment-list');
            }
            if( ! in_array($employment->status, [Employment::StatusConfirm])) {
                return $this->actionEmploymentRecharge();
            }
            return $this->render('employment-order', [
                'employment' => $employment,
            ]);
        }
        if(empty($employment)) {
            return $this->json('Invalid.Employment', '无效的雇佣信息');
        }
        if( ! in_array($employment->status, [Employment::StatusConfirm])) {
            return $this->json('System.Error', '确认订单失败，请刷新页面重试');
        }
        $params = $this->request->post();
        $checker = Checker::authentication(Employment::flyer('order'), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if( ! $employment->paying($params['coupon_id'])) {
            return $this->json('System.Error', '确认订单失败，请稍后重试');
        }
        return $this->json(SuccessCode, '确认订单成功，请尽快支付');
    }
    public function actionEmploymentCouponDeduct()
    {

        if( ! $employment = Employment::canEdit($this->request->get('id'), ['employer_id' => $this->user->id])) {
            return $this->json('Invalid.Employment', '无效的雇佣信息');
        }
        $params = $this->request->post();
        $checker = Checker::authentication(Employment::flyer('order'), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        $userCoupon = UserCoupon::findOne($params['coupon_id']);
        if(empty($userCoupon->coupon)) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        $order = [
            'amount' => $employment->total_amount,
        ];
        if( ! $userCoupon->usable($order)) {
            return $this->json('Invalid.Coupon', '无效的优惠劵');
        }
        return $this->json(['deduct' => bcdiv($userCoupon->deduct($order), 100, 2)]);
    }
    /**
     * 支付雇佣订单
     * @return mixed
     */
    public function actionEmploymentRecharge()
    {
        $employment = Employment::canEdit($this->request->get('id'), ['employer_id' => $this->user->id]);
        if( ! $this->request->isPost) {
            if(empty($employment)) {
                return $this->error('无效的雇佣信息（Invalid Employment）', 'employer/employment-list');
            }
            if( ! in_array($employment->status, [Employment::StatusPaying])) {
                return $this->error('当前雇佣订单不能支付（Invalid Employment）', 'employer/employment-list');
            }
            return $this->render('employment-recharge', [
                'employment' => $employment,
            ]);
        }
        if(empty($employment)) {
            return $this->json('Invalid.Employment', '无效的雇佣信息');
        }
        if( ! in_array($employment->status, [Employment::StatusPaying])) {
            return $this->json('Invalid.Employment', '当前雇佣订单不能支付');
        }
        $params = $this->request->post();
        $checker = Checker::authentication(EmploymentRecharge::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        $attributes = [
            'employment_id' => $employment->id,
            'platform' => $params['platform'],
            'amount' => $employment->payAmount(),
            'remark' => '支付雇佣金',
        ];
        if( ! ($recharge = EmploymentRecharge::creator($attributes))) {
            return $this->json('System.Error', '发起支付失败，请稍后重试');
        }
        $params = [
            'order_number' => $recharge->order_number,
            'amount' => $recharge->amount,
        ];
        $service = new RechargeServer($recharge->platform);
        $response = $service->recharge($params);
        Yii::info('返回数据：'.json_encode($response));

        if($service->success()) {
            return $this->json(SuccessCode, '请尽快完成支付', [
                'order_number' => $recharge->order_number,
                'payment' => $response['payment'],
                'javascript' => $response['javascript'],
            ]);
        }
        return $this->json('System.Error', '发起支付失败，请稍后重试');
    }
    /**
     * 暂停雇佣服务
     * @return mixed
     */
    public function actionEmploymentPause()
    {
        $params = $this->request->post();
        $checker = Checker::authentication(EmploymentPause::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if( ! $employment = Employment::canEdit($params['employment_id'], ['employer_id' => $this->user->id])) {
            return $this->json('Invalid.Employment', '无效的雇佣信息（Invalid Employment）');
        }
        if($employment->applyPause($params)) {
            return $this->json(SuccessCode, '申请暂停成功，请等待设计师确认');
        }
        return $this->json('System.Error', '申请暂停失败，请稍后重试');
    }

    /**
     * 雇佣服务申诉
     * @return mixed
     */
    public function actionEmploymentAppeal()
    {
        $params = $this->request->post();
        $checker = Checker::authentication(EmploymentAppeal::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if( ! $employment = Employment::canEdit($params['employment_id'], ['employer_id' => $this->user->id])) {
            return $this->json('Invalid.Employment', '无效的雇佣信息（Invalid Employment）');
        }
        $params['handler'] = EmploymentAppeal::HandlerEmployer;
        if($employment->applyAppeal($params)) {
            return $this->json(SuccessCode, '申诉成功，请耐心等待');
        }
        return $this->json('System.Error', '申诉失败，请稍后重试');
    }
    /**
     * 评价雇佣服务
     * @return mixed
     */
    public function actionEmploymentEvaluate()
    {
        $params = $this->request->post();
        $checker = Checker::authentication(UserEvaluate::flyer(), $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if( ! $employment = Employment::canEdit($params['employment_id'], ['employer_id' => $this->user->id])) {
            return $this->json('Invalid.Employment', '无效的雇佣信息（Invalid Employment）');
        }
        $params['user_id'] = $employment->designer_id;
        if(UserEvaluate::creator($params)) {
            return $this->json(SuccessCode, '评价成功');
        }
        return $this->json('System.Error', '评价失败，请稍后重试');
    }
    /**
     * 暂停雇佣服务
     * @return mixed
     */
    public function actionEmploymentConfirmPayment()
    {
        $params = $this->request->post();
        if( ! $employment = Employment::canEdit($params['employment_id'], ['employer_id' => $this->user->id])) {
            return $this->json('Invalid.Employment', '无效的雇佣信息（Invalid Employment）');
        }
        if($employment->confirmPayment($params)) {
            return $this->json(SuccessCode, '确认发薪成功');
        }
        return $this->json('System.Error', '确认发薪失败，请稍后重试');
    }
    /**
     * 我的收藏 - 设计师
     * @return mixed
     */
    public function actionCollectionDesignerList()
    {
        if( ! $this->request->isPost) {
            return $this->render('collection-designer-list');
        }
        $params['type'] = UserCollection::TypeDesigner;
        $params['user_id'] = $this->user->id;
        $query = UserCollection::filterConditions(UserCollection::initCondition(['user_id', 'type'], $params));
        // $data['sql'] = $query->createCommand()->getRawSql();
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')
            ->offset(Pager::offset())->limit(Pager::limit())
            ->asArray()->all();
        $data['designer'] = ArrayHelper::index(User::find()->select('id, photo, gender, work_life, nickname, realname, skills, salary, star')
            ->where(['id' => ArrayHelper::getColumn($data['infos'], 'collection_id')])
            ->with('styles')->with('categories')
            ->asArray()->all(), 'id');
        foreach($data['designer'] as & $designer) {
            $designer['stylesString'] = implode(',', ArrayHelper::getColumn($designer['styles'], 'category_id'));
            $designer['categoriesString'] = implode(',', ArrayHelper::getColumn($designer['categories'], 'category_id'));
        }
        return $this->json($data);
    }

    /**
     * 我的收藏 - 作品
     * @return mixed
     */
    public function actionCollectionDesignList()
    {
        if( ! $this->request->isPost) {
            return $this->render('collection-design-list');
        }
        $params['type'] = UserCollection::TypeDesign;
        $params['user_id'] = $this->user->id;
        $query = UserCollection::filterConditions(UserCollection::initCondition(['user_id', 'type'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('designer')->with('design')
            ->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())
            ->asArray()->all();
        return $this->json($data);
    }

    /**
     * 我的优惠劵
     * @return mixed
     */
    public function actionCouponList()
    {
        if( ! $this->request->isPost) {
            return $this->render('coupon-list');
        }
        $params['user_id'] = $this->user->id;
        $query = UserCoupon::filterConditions(UserCoupon::initCondition(['user_id'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('coupon')
            ->orderBy(new Expression('status = '.UserCoupon::StatusUsable.' desc, status desc, id desc'))
            ->offset(Pager::offset())->limit(Pager::limit())
            ->asArray()->all();
        foreach($data['infos'] as & $coupon) {
            $coupon['deduct'] = Coupon::deductText($coupon['coupon']);
        }
        return $this->json($data);
    }
    /**
     * 邀请有礼雇主详情页
     */
    public function actionInvitesCourtesy()
    {

        $invitingcode = $this->user->invitingcode();
        return $this->render('invites-courtesy', ['invitingcode' =>$invitingcode]);
    }
}